# -*- coding: utf-8 -*-

from rest_framework.decorators import action
from core.viewset import CustomModelViewSet
from core.response import JsonResponse
from .models import Requirement
from .serializers import *
from .resources import *
from .filters import *
from .permission import *
from utils.tree import list2tree


class RequirementViewSet(CustomModelViewSet):
    """
    需求管理接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = Requirement.objects.all()
    serializer_class = RequirementSerializer
    list_serializer_class = ListRequirementSerializer
    create_serializer_class = CreateUpdateRequirementSerializer
    update_serializer_class = CreateUpdateRequirementSerializer
    filterset_class = RequirementFilterSet
    import_resources = RequirementResouces
    export_resources = RequirementResouces
    permission_classes = [RequirementPermission]

    @action(detail=False, methods=["GET"])
    def treeselect(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = RequirementTreeSelectSerializer(
            queryset, many=True, request=request
        )
        data = list2tree(serializer.data)
        return JsonResponse(data=data, msg="获取成功")
